
//
//  HomeViewController.m
//  weibo-01
//
//  Created by HZApple on 16/5/9.
//  Copyright © 2016年 hdu. All rights reserved.
//

#import "HomeViewController.h"
#import "SinaWeibo.h"
#import "AppDelegate.h"
#import "ThemeManager.h"
#import "ThemeLabel.h"
#import "WeiboModel.h"
#import "YYModel.h"
#import "WeiboCellLayout.h"
#import "WXRefresh.h"
#import "ThemeImageView.h"
#import <MediaToolbox/MediaToolbox.h>
#import "MBProgressHUD.h"


@interface HomeViewController ()<SinaWeiboDelegate, SinaWeiboRequestDelegate>

@property (nonatomic, strong)NSMutableArray *weiboList;

@property (nonatomic, strong) ThemeImageView *notifyImgView;

@end

@implementation HomeViewController

- (ThemeImageView *)notifyImgView {
    if (_notifyImgView == nil) {
        
        _notifyImgView = [[ThemeImageView alloc] initWithFrame:CGRectMake(10, -40, kScreenWidth - 20, 40)];
        _notifyImgView.imageName = @"timeline_notify.png";
        
        [self.view addSubview:_notifyImgView];
        
        ThemeLabel *label = [[ThemeLabel alloc] initWithFrame:_notifyImgView.bounds];
        
        label.colorName = @"Mask_Notice_color";
        
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 1001;
        
        [_notifyImgView addSubview:label];
        
    }
    return _notifyImgView;
}

- (NSMutableArray *)weiboList {
    
    if (_weiboList == nil) {
        _weiboList = [NSMutableArray array];
        
    }
    
    return _weiboList;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"首页";
    
     //self.navigationController.navigationBar.translucent = NO;
    
    
    [_weiboTableView addPullDownRefreshBlock:^{
        [self _loadNewWeibo];
        
    }];
    [_weiboTableView addInfiniteScrollingWithActionHandler:^{
        [self _loadNextWeibo];
    }];
    
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    sinaweibo.delegate = self;
    if (!(sinaweibo.isAuthValid)) {
        
        [sinaweibo logIn];
        
    }
    
    else { 
        
        NSDictionary *params = @{
                                 @"count" : @"10"
                                 
                                 };
        
       SinaWeiboRequest *request =   [sinaweibo requestWithURL:@"statuses/home_timeline.json" params:[params mutableCopy] httpMethod:@"GET" delegate:self];
        request.tag = WeiboRequestNormal;
        
        [self showHUDLoadingView];
        
        self.weiboTableView.hidden = YES;
        
    }
    
}



- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}

- (void)_loadNewWeibo {
    
    WeiboCellLayout *layout = [self.weiboList firstObject];
    NSString *string = layout.weibo.idstr;
    
    NSDictionary *pragama = @{
                              @"since_id":string
                              };
    
   SinaWeiboRequest *request = [[self sinaweibo] requestWithURL:@"statuses/home_timeline.json" params:[pragama mutableCopy] httpMethod:@"GET" delegate:self];
    request.weiboTag = WeiboRequestNew;
    
}

- (void)_loadNextWeibo {
    WeiboCellLayout *layout = [self.weiboList lastObject];
    NSString *string = layout.weibo.idstr;
    
    NSDictionary *pragama = @{
                              @"max_id":string,
                              @"count" : @"10"
                              };
    
    SinaWeiboRequest *request = [[self sinaweibo] requestWithURL:@"statuses/home_timeline.json" params:[pragama mutableCopy] httpMethod:@"GET" delegate:self];
    request.weiboTag = WeiboRequestNextPage;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.weiboTableView reloadData];
    
}

#pragma mark - SinaWeiboDelegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo {
    
    //存储Oauth认证的相关信息
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - SinaWeiboRequestDelegate
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    
    NSLog(@"%@", error);
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
    
   // NSLog(@"%@", result);
   
    
    NSArray *statuses = result[@"statuses"];
    
    NSMutableArray *temp = [NSMutableArray array];
    
    for (NSDictionary *status in statuses) {
        WeiboModel *weibo = [WeiboModel yy_modelWithDictionary:status];
        WeiboCellLayout *layout = [[WeiboCellLayout alloc] init];
        layout.weibo = weibo;
        [temp addObject:layout];
    }
    if(request.weiboTag == WeiboRequestNormal) {
        
        [self hideHUDLoadingView];
        self.weiboTableView.hidden = NO;
        self.weiboList = temp;
    }else if (request.weiboTag == WeiboRequestNew) {
        
        [self showNotifyView:temp.count];
        
        
        NSRange range = NSMakeRange(0, temp.count);
        NSIndexSet *set = [[NSIndexSet alloc] initWithIndexesInRange:range];
       [self.weiboList insertObjects:temp atIndexes:set];
        [self.weiboTableView.pullToRefreshView stopAnimating];
    }else if (request.weiboTag == WeiboRequestNextPage) {
        
        WeiboCellLayout *firstLayout = [temp firstObject];
        WeiboCellLayout *lastLayout = [self.weiboList lastObject];
        
        if ([firstLayout.weibo.idstr isEqualToString:lastLayout.weibo.idstr]) {
            [_weiboList removeLastObject];
        }
        
        
        [self.weiboList addObjectsFromArray:temp];
        [self.weiboTableView.infiniteScrollingView stopAnimating];
    }
    
    
    self.weiboTableView.weibolist = self.weiboList;
    
    [self.weiboTableView reloadData];
}

- (void)showNotifyView:(NSInteger)count {
    
    if (count <= 0) {
        return;
    }
    
    //设置label的显示内容
    ThemeLabel *label = (ThemeLabel *)[self.notifyImgView viewWithTag:1001];
    
    label.text = [NSString stringWithFormat:@"%ld 条新微博", count];
    
    //加动画效果
    [UIView animateWithDuration:0.3 animations:^{
        self.notifyImgView.transform = CGAffineTransformMakeTranslation(0, 50);
    } completion:^(BOOL finished) {
        
        [UIView animateKeyframesWithDuration:0.3 delay:0.8 options:UIViewKeyframeAnimationOptionLayoutSubviews  animations:^{
            self.notifyImgView.transform = CGAffineTransformIdentity;
        } completion:NULL];
        
        
    }];
    
    //播放声音-->注册成系统声音
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"msgcome.wav" ofType:nil];
    
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    
    SystemSoundID soundID = 0;
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &soundID);
    
    AudioServicesPlaySystemSound(soundID);
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    
//    static BOOL flag = YES;
//    
//    [ThemeManager sharedManager].themeName = flag ?  @"Happy Toy" : @"猫爷";
//    
//    flag = !flag;
//    
//}

@end
